import { message } from 'antd';
import { addProduct, deleteProduct, queryProduct, updateProduct } from '@/pages/product/services';

export default {
  namespace: 'product',
  state: {
    keyword: '',
    pageInfo: {
      current: 1,
      pageSize: 10,
      total: 0,
    },
    data: [],
  },
  effects: {
    *QueryProduct(_, { call, put, select }) {
      const {
        keyword,
        pageInfo: { current, pageSize },
      } = yield select(({ product }) => product);
      const res = yield call(queryProduct, { pageIndex: current, pageSize, keyword });
      if (!res) {
        return;
      }
      const { data, total } = res;
      yield put({
        type: 'gotProduct',
        data,
        total,
      });
    },
    /**
     * @return {boolean | void}
     */
    *AddProduct({ product }, { call }) {
      const res = yield call(addProduct, product);
      if (!res) {
        return;
      }
      const { success } = res;
      if (!success) {
        message.error('添加失败');
        return;
      }
      message.success('添加成功');
      // eslint-disable-next-line consistent-return
      return true;
    },
    /**
     * @return {boolean | void}
     */
    *UpdateProduct({ product }, { call }) {
      const res = yield call(updateProduct, product);
      if (!res) {
        return;
      }
      const { success } = res;
      if (!success) {
        message.error('更新失败');
        return;
      }
      message.success('更新成功');
      // eslint-disable-next-line consistent-return
      return true;
    },
    /**
     * @return {boolean | void}
     */
    *DeleteProduct({ id }, { call }) {
      const res = yield call(deleteProduct, id);
      if (!res) {
        return;
      }
      const { success } = res;
      if (!success) {
        message.error('删除失败');
        return;
      }
      message.success('删除成功');
      // eslint-disable-next-line consistent-return
      return true;
    },
  },
  reducers: {
    gotProduct(state, { data, total }) {
      return { ...state, data, pageInfo: { ...state.pageInfo, total } };
    },
    syncPageInfo(state, { pageInfo }) {
      return { ...state, pageInfo: { ...state.pageInfo, ...pageInfo } };
    },
    syncKeyword(state, { keyword }) {
      return { ...state, keyword };
    },
  },
};
